"""
应用相关路由
"""

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from typing import List

from database import get_db
from models.common import StandardResponse
from models.app import Application, AppCategory
from services.auth_service import get_current_user
from services.app_service import AppService

router = APIRouter(prefix="/apps", tags=["应用"])

@router.get("/list", response_model=StandardResponse, summary="获取应用列表")
async def get_apps_list(
    category_id: int = None,
    page: int = 1,
    page_size: int = 20,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    获取应用列表
    
    - **category_id**: 分类ID（可选）
    - **page**: 页码
    - **page_size**: 每页数量
    """
    try:
        app_service = AppService(db)
        apps_data = await app_service.get_apps_list(
            category_id=category_id,
            page=page,
            page_size=page_size
        )
        
        return StandardResponse(
            success=True,
            message="获取应用列表成功",
            data=apps_data
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取应用列表失败: {str(e)}"
        )

@router.get("/categories", response_model=StandardResponse, summary="获取应用分类")
async def get_app_categories(
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    获取应用分类列表
    """
    try:
        app_service = AppService(db)
        categories = await app_service.get_categories()
        
        return StandardResponse(
            success=True,
            message="获取应用分类成功",
            data=categories
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取应用分类失败: {str(e)}"
        )

@router.post("/favorites", response_model=StandardResponse, summary="保存常用应用")
async def save_favorite_apps(
    app_ids: List[int],
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    保存用户常用应用
    
    - **app_ids**: 应用ID列表
    """
    try:
        app_service = AppService(db)
        await app_service.save_user_favorites(current_user["id"], app_ids)
        
        return StandardResponse(
            success=True,
            message="保存常用应用成功"
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"保存常用应用失败: {str(e)}"
        )

@router.get("/favorites", response_model=StandardResponse, summary="获取常用应用")
async def get_favorite_apps(
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    获取用户常用应用
    """
    try:
        app_service = AppService(db)
        favorites = await app_service.get_user_favorites(current_user["id"])
        
        return StandardResponse(
            success=True,
            message="获取常用应用成功",
            data=favorites
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取常用应用失败: {str(e)}"
        )

@router.post("/sort", response_model=StandardResponse, summary="应用排序")
async def sort_apps(
    app_orders: List[dict],
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    应用排序
    
    - **app_orders**: 应用排序列表 [{"app_id": 1, "sort_order": 1}, ...]
    """
    try:
        app_service = AppService(db)
        await app_service.update_app_sort_order(current_user["id"], app_orders)
        
        return StandardResponse(
            success=True,
            message="应用排序成功"
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"应用排序失败: {str(e)}"
        )